package com.camerareader.mvp.main_page;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.mtp.MtpObjectInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.camerareader.App;
import com.camerareader.BuildConfig;
import com.camerareader.R;
import com.camerareader.mvp.BaseActivity;
import com.camerareader.mvp.OrderInfoActivity;
import com.camerareader.mvp.OrderInfoModel;
import com.camerareader.mvp.image_list_page.ImageListActivity;
import com.camerareader.mvp.login_page.LoginActivity;
import com.camerareader.mvp.setting_page.SettingActivity;
import com.camerareader.mvp.two_d_page.TwoDActivity;
import com.camerareader.upload_list.UploadService;
import com.camerareader.util.CompletedView;
import com.camerareader.util.SharedPreferencesUtil;
import com.fileoperation.BaseSetting;
import com.fileoperation.CommonUtils;
import com.fileoperation.FileTools;
import com.fileoperation.model.LogOutEvent;
import com.fileoperation.model.Photo;
import com.fileoperation.model.SpaceFullEvent;
import com.fileoperation.model.StateChangedEvent;
import com.fileoperation.user.UserInfo;
import com.fileoperation.user.UserInfoParser;
import com.jakewharton.rxbinding.view.RxView;
import com.nettools.Constants;
import com.nettools.NetUtils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements MainActivityContract.View {
    private static final int REQUEST_CODE_SCAN = 1;
    private MainActivityContract.Presenter mPresenter;
    private View totalPhotoView,sparePhotoView,queuePhotoView;
    private TextView totalPhoto;
    private TextView queuePhoto;
    private TextView sparePhoto;
    private TextView appMode;
    private TextView usbState;
    private TextView useCondition;
    private CompletedView deskCv;
    private TextView deskData;
    private TextView loginoutTv;
    private TextView scanCodeTv;
    private ImageView imageView;
    private ImageView imageSelect;
    private View setting;
    private boolean isReady = false;
    private Photo photo;
    private final int requestExternalStoragePermission = 1;

    private boolean fromLogin;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initService();


        mPresenter = new MainActivityPresenter();
        mPresenter.onCreate(this);

        initView();

        initData();

        initPermission();
        fromLogin = getIntent().getBooleanExtra("fromLogin",false);
        if(fromLogin){
            startScan();
        }
    }

    private void initService() {
        Constants.PHOTO_FOLDER = SharedPreferencesUtil.get("uploadUrl","");
        Intent serviceIntent = new Intent(this, UploadService.class);
        startService(serviceIntent);
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean granted) {
                            if (granted){
                                initDir();
                            }else {
                                Toast.makeText(MainActivity.this, "无法访问存储设备将导致无法传输图片，请前往设置中心开启权限！", Toast.LENGTH_SHORT).show();
                                useCondition.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.warning));
                                useCondition.setText("没有权限操作sd卡，请在设置中开放权限！");
                                isReady = false;
                            }
                        }
                    });
        }else {
            initDir();
        }

    }

    private void initDir() {
        if (FileTools.initDir()){
            if (!FileTools.isSpaceEnough()){
                Toast.makeText(MainActivity.this, "存储空间不足，请前往清理，否则将无法正常使用", Toast.LENGTH_SHORT).show();
                useCondition.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.warning));
                useCondition.setText("存储空间不足，请前往清理，否则将无法正常使用！");
                isReady = false;
            }else {
                useCondition.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                useCondition.setText("环境正常！");
                isReady = true;
                refreshCurrentState();
            }
        }else {
            Toast.makeText(MainActivity.this, "创建应用私有文件夹失败！", Toast.LENGTH_SHORT).show();
            useCondition.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.warning));
            useCondition.setText("文件夹创建失败，请重试！");
            isReady = false;
        }
        long total = FileTools.getTotalSize(FileTools.DIR_PATH);
        long availabSize = FileTools.getAvailableSize(FileTools.DIR_PATH);
        deskData.setText(FileTools.formatSize(availabSize));
        deskCv.setText(FileTools.formatSize(total));
        int progress = (int)( (availabSize*1.0f)/(total*1.0f) * 100);
        deskCv.setProgress(progress);
    }


    private void initData() {
        mPresenter.startScan();
    }

    private void initView() {
        getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
        imageView = findViewById(R.id.imageView);
        imageSelect = findViewById(R.id.imageSelect);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(photo != null){
                    photo.setCheck(!photo.isCheck());
                    imageSelect.setImageResource(photo.isCheck() ? R.drawable.selected_state : 0);
                }else{
                    imageSelect.setImageResource(0);
                }

            }
        });
        deskData  = (TextView) findViewById(R.id.desk_data);
        deskCv = findViewById(R.id.deskCv);
        loginoutTv = findViewById(R.id.loginoutTv);
        loginoutTv.setText(UserInfo.getInstance().getUsername()+",退出");
        findViewById(R.id.loginoutTv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginout();
            }
        });

        totalPhoto = (TextView) findViewById(R.id.total_photo);
        setStatusText(String.valueOf(00), getResources().getString(R.string.total_photo), totalPhoto);
        totalPhotoView = findViewById(R.id.total_photo_layout);
        RxView.clicks(totalPhotoView).throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (isReady){
                            ImageListActivity.navigateImageListActivity(MainActivity.this, ImageListActivity.TOTAL_MODE);
                        }
                    }
                });

        queuePhoto = (TextView) findViewById(R.id.queue_photo);
        setStatusText(String.valueOf(00), getResources().getString(R.string.queue_photo), queuePhoto);
        queuePhotoView = findViewById(R.id.queue_photo_layout);
        RxView.clicks(queuePhotoView).throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (isReady){
                            ImageListActivity.navigateImageListActivity(MainActivity.this, ImageListActivity.UPLOAD_MODE);
                        }
                    }
                });
        sparePhoto = (TextView) findViewById(R.id.spare_photo);
        setStatusText(String.valueOf(00), getResources().getString(R.string.spare_photo), sparePhoto);
        sparePhotoView = findViewById(R.id.spare_photo_layout);
        RxView.clicks(sparePhotoView).throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (isReady){
                            ImageListActivity.navigateImageListActivity(MainActivity.this, ImageListActivity.SPARE_MODE);
                        }
                    }
                });

        appMode = (TextView) findViewById(R.id.app_mode);

        setting = findViewById(R.id.go_setting);
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SettingActivity.navigateSettingPage(MainActivity.this);
            }
        });
        usbState = (TextView) findViewById(R.id.usb_state);

//        twoD = findViewById(R.id.two_d);
//        RxView.clicks(twoD).throttleFirst(1, TimeUnit.SECONDS)
//                .subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//                        TwoDActivity.navigateTwoDActivity(MainActivity.this);
//                    }
//                });

        useCondition = (TextView) findViewById(R.id.use_condition);
        useCondition.setText("未连接");

        scanCodeTv = findViewById(R.id.scanCodeTv);
        scanCodeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onScan();
            }
        });

        findViewById(R.id.confirm_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Constants.PHOTO_FOLDER == null || Constants.PHOTO_FOLDER.length() < 1){
                    Toast.makeText(MainActivity.this, "请先拍摄订单", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(totalList != null){
                    for(Photo temp : totalList){
                        if(temp.isCheck()){
                            uploadService.addTask(photo);
                        }
                    }
                    Toast.makeText(MainActivity.this, "已添加上传列表", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "没有可上传文件", Toast.LENGTH_SHORT).show();
                }
            }
        });

        leftIb = findViewById(R.id.leftIb);
        leftIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageIndex--;
                nextImage();
            }
        });

        rightIb = findViewById(R.id.rightIb);
        rightIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageIndex++;
                nextImage();
            }
        });

    }

    void loginout(){
        if(totalList != null && totalList.size() > 0){
            android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
            dialog.setMessage("仍有照片未上传，退出将清空所有照片");
            dialog.setPositiveButton("清除", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    uploadService.clearUploadList();
                    FileTools.deleteAllPhotos();
                    UserInfo.getInstance().clearUserInfo(MainActivity.this);
                    LoginActivity.navigateLoginActivity(MainActivity.this);
                    MainActivity.this.finish();
                }
            });
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();;
                }
            });
            dialog.show();
        }else{
            uploadService.clearUploadList();
            FileTools.deleteAllPhotos();
            UserInfo.getInstance().clearUserInfo(MainActivity.this);
            LoginActivity.navigateLoginActivity(MainActivity.this);
            MainActivity.this.finish();
        }
    }

    private int imageIndex = 0;
    private ImageButton rightIb,leftIb;
    private void nextImage(){
        if(totalList != null && totalList.size() > 0){
            if(imageIndex >= totalList.size()-1){
                imageIndex = totalList.size()-1;
                rightIb.setVisibility(View.INVISIBLE);
            }
            if(imageIndex <= 0){
                imageIndex = 0;
                leftIb.setVisibility(View.INVISIBLE);
            }
            if(totalList.size() == 1){
                rightIb.setVisibility(View.INVISIBLE);
                leftIb.setVisibility(View.INVISIBLE);
            }else{
                if(imageIndex > 0){
                    leftIb.setVisibility(View.VISIBLE);
                }
                if(imageIndex < totalList.size()-1){
                    rightIb.setVisibility(View.VISIBLE);
                }
            }
            photo = totalList.get(imageIndex);
            Glide.with(MainActivity.this).load(new File(photo.getPath() + photo.getFileName()))
                    .placeholder(ContextCompat.getDrawable(MainActivity.this, 0))
//                    .centerCrop()
                    .into(imageView);
            imageSelect.setImageResource(photo.isCheck() ? R.drawable.selected_state : 0);
        }else{
            rightIb.setVisibility(View.INVISIBLE);
            leftIb.setVisibility(View.INVISIBLE);
            photo = null;
            imageSelect.setImageResource( 0);
            imageView.setImageResource(R.drawable.image_placeholder);
        }
    }

    private void onScan(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            new RxPermissions(this).request(Manifest.permission.CAMERA)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean granted) {
                            if (granted){
                                startScan();
                            }else {
                                Toast.makeText(MainActivity.this, "无法访问相机功能", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }else {
            startScan();
        }
    }

    private void startScan(){
        if(BuildConfig.DEBUG){
//            orderInfo("424P2800D4XR48X");
//            return;
        }
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
         /*ZxingConfig是配置类  可以设置是否显示底部布局，闪光灯，相册，是否播放提示音  震动等动能
         * 也可以不传这个参数
         * 不传的话  默认都为默认不震动  其他都为true
         * */

        ZxingConfig config = new ZxingConfig();
        //config.setShowbottomLayout(true);//底部布局（包括闪光灯和相册）
        config.setPlayBeep(true);//是否播放提示音
        config.setShake(true);//是否震动
        //config.setShowAlbum(true);//是否显示相册
        config.setShowFlashLight(true);//是否显示闪光灯
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
//                result.setText("扫描结果为：" + content);
                String lastOrderId = SharedPreferencesUtil.get("orderId","");
                if(lastOrderId != null && !lastOrderId.equals(content) && uploadService.getQueueNum() > 0){
                    android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
                    dialog.setMessage("仍有照片未上传，进入新订单将清空所有照片");
                    dialog.setPositiveButton("清除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            uploadService.clearUploadList();
                            FileTools.deleteAllPhotos();
                        }
                    });
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();;
                        }
                    });
                    dialog.show();
                }else{
                    orderInfo(content);
                }

            }
        }
    }

    private void orderInfo(final String orderInfo){

        Observable.create(new Observable.OnSubscribe<JSONObject>() {
            @Override
            public void call(Subscriber<? super JSONObject> subscriber) {
                try {
                    Response response = NetUtils.getInstance().getOrderInfo(orderInfo);
                    JSONObject json = new JSONObject(response.body().string());
                    System.out.println(json.toString());
                    if (json.optBoolean("State")){
                        subscriber.onNext(json);
                    }else {
                        subscriber.onError(new Exception(json.optString(Constants.MSG)));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                subscriber.unsubscribe();
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<JSONObject>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        SharedPreferencesUtil.put("orderId",orderInfo);
                        String json = jsonObject.opt("Data").toString();
                        OrderInfoModel model = OrderInfoModel.orderInfoModelWithJSON(json);
                        Constants.PHOTO_FOLDER = model.Shot_Upload_Url;
                        SharedPreferencesUtil.put("uploadUrl",Constants.PHOTO_FOLDER);
                        if(model.Order_State == 1 || model.Order_State == 2){
                            Intent intent = new Intent(MainActivity.this,OrderInfoActivity.class);
                            intent.putExtra("orderId",orderInfo);
                            intent.putExtra("orderModel",model);
                            startActivity(intent);
                        }else{
                            Toast.makeText(MainActivity.this, "请开始拍照", Toast.LENGTH_SHORT).show();
                        }
                    }
                });


    }

    private void setStatusText(String num, String name, TextView textView){
//        String text = num + "\n" + name;
//        SpannableString newText = new SpannableString(text);
//        newText.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.gray_color)), text.length() - name.length(), text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        newText.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.indicate_name_text_size)), text.length() - name.length(), text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        textView.setText(newText);
        textView.setText(num);
    }

    private ArrayList<Photo> totalList;
    private void refreshCurrentState(){
        int totalFileNum = FileTools.getTotalFileNum();
        int queueNum;
        if (uploadService != null){
            queueNum = uploadService.getQueueNum();
        }else {
            queueNum = 0;
        }
        setStatusText(String.valueOf(totalFileNum), getResources().getString(R.string.total_photo), totalPhoto);
        setStatusText(String.valueOf(queueNum), getResources().getString(R.string.queue_photo), queuePhoto);
        setStatusText(String.valueOf(totalFileNum - queueNum), getResources().getString(R.string.spare_photo), sparePhoto);
        resetUploadMode();
        setUsbState(BaseSetting.getInstance().isUsbAvailable());


        totalList =  getSparePhotos();
        if(totalList != null){
            imageIndex = totalList.size()-1;
        }
        nextImage();
    }

    private ArrayList<Photo> getSparePhotos(){
        ArrayList<Photo> totalList = FileTools.getTotalImageList();
        ArrayList<Photo> uploadList = uploadService != null ? uploadService.getQueueList() : null;
        if (uploadList == null) return totalList;
        if (totalList == null) return null;
        for (int i = 0; i <uploadList.size(); i++){
            Photo photo = uploadList.get(i);
            if (totalList.contains(photo)){
                totalList.remove(photo);
            }
        }
        return totalList;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStateChanged(StateChangedEvent event){
        refreshCurrentState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSpaceFull(SpaceFullEvent event){
        Toast.makeText(this, "存储空间满了，请马上前去释放空间！", Toast.LENGTH_SHORT).show();
    }



    @Override
    protected void onServiceConnected() {
        refreshCurrentState();
    }

    @Override
    protected void onServiceDisconnected() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!UserInfo.getInstance().isLogin()){
            EventBus.getDefault().post(new LogOutEvent());
            LoginActivity.navigateLoginActivity(MainActivity.this);
            finish();
        }
        resetUploadMode();
        refreshCurrentState();
    }

    private void resetUploadMode() {
        appMode.setText(BaseSetting.getInstance().isAutoMode() ? getResources().getText(R.string.at) : getResources().getText(R.string.mt));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
        stopService(serviceIntent);
    }



    @Override
    public void setImageList(ArrayList<MtpObjectInfo> list) {

    }

    @Override
    public void setLoadingProgress(boolean show) {
    }

    @Override
    public void onSaveCompleted() {
    }

    @Override
    public void setSaveResponse(int index, int total, boolean success) {

    }


    public void setUsbState(boolean linked) {
        usbState.setText(linked ? getResources().getText(R.string.usb_linked): getResources().getText(R.string.usb_unlinked));
    }


    public static void navigateMainActivity(Activity activity){
        Intent intent = new Intent(activity, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if(activity.getClass().equals(LoginActivity.class)){
            intent.putExtra("fromLogin",true);
        }
        activity.startActivity(intent);
    }



}
